#pragma once
#include"Stack.h"

void Stack::Init(int N)
{
	_a = (STDataType*)malloc(N * sizeof(int));
	if (_a == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	_top = 0;
	_capacity = N;
}

void Stack::Capacity()
{
	if (_top == _capacity)
	{
		int _newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
		STDataType* tmp = (STDataType*)realloc(_a, _newcapacity * sizeof(int));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		_a = tmp;
		_capacity = _newcapacity;
	}
}

void Stack::Push(STDataType x)
{
	Capacity();
	_a[_top] = x;
	_top++;
}

void Stack::Pop()
{
	assert(!Empty());
	_top--;
}

int Stack::Top()
{
	assert(!Empty());
	return _a[_top - 1];
}

bool Stack::Empty()
{
	return _top == 0;
}

int Stack::Find(STDataType x)
{
	for (int i = 0; i < _top; ++i)
	{
		if (_a[i] == x)
		{
			return _a[i];
		}
	}
	return -1;
}


STDataType& Stack::At(size_t pos)
{
	assert(!Empty());
	assert(pos < _top);

	return _a[pos];
}

int Stack::Size()
{
	return _top;
}

void Stack::Print()
{
	for (int i = 0; i < _top; ++i)
	{
		cout << _a[i] << " ";
	}
	cout << endl;
}

void Stack::Destory()
{
	free(_a);
	_a = NULL;
	_top = _capacity = 0;
}